package com.jfire.socket.socketserver.handler.impl;

import java.nio.charset.Charset;
import javax.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.jfire.baseutil.collection.ByteBufferPool;
import com.jfire.json.JsonUtil;
import com.jfire.socket.socketserver.bus.BusinessCommand;
import com.jfire.socket.socketserver.bus.Message;
import com.jfire.socket.socketserver.bus.ServerChannelInfo;
import com.jfire.socket.socketserver.bus.ServerStatusData;
import com.jfire.socket.socketserver.handler.MessageHandler;
import com.jfire.socket.socketserver.transfer.server.ServerStatus;

@Resource
public class StatusHandler implements MessageHandler
{
    @Resource
    private ServerStatus  serverStatus;
    private static Logger logger  = LogManager.getLogger();
    private Charset       charset = Charset.forName("utf-8");
    
    @Override
    public byte interestedDataPacketType()
    {
        return BusinessCommand.SERVER_STATUS;
    }
    
    @Override
    public void handler(Message message)
    {
        logger.debug("进行服务器状态查询");
        try
        {
            ServerStatusData statusData = new ServerStatusData();
            int count = serverStatus.getMessages().size();
            int serverMemory = 0;
            for (ServerChannelInfo each : serverStatus.getMessages())
            {
                serverMemory += each.getReadBuffer().capacity();
                statusData.getConnectMap().put(each.getAddress(), each.getReadBuffer().capacity() / 1024 + "K");
            }
            statusData.setJvmMem(String.valueOf(Runtime.getRuntime().totalMemory() / 1024 / 1024) + "M");
            statusData.setCacheMap(ByteBufferPool.getCacheStatus());
            statusData.setServerMemory(serverMemory);
            statusData.setNowConnect(count);
            statusData.setBufferCacheSize(ByteBufferPool.getBufferCacheSize());
            String reply = JsonUtil.toJsonString(statusData);
            message.getBusinessData().clear().putArray(reply.getBytes(charset)).startRead(0);
        }
        catch (Throwable e)
        {
            logger.error("查询服务器状态异常", e);
            message.getChannelInfo().close();
        }
    }
    
}
